package com.steve.summary.saga.common.repository;

import com.steve.summary.saga.common.model.Inventory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.LockModeType;
import java.util.Optional;

/**
 * @Author: STEVE
 * @Description: 库存数据访问接口，包含库存扣减和恢复操作
 * @since: 2025-05-28
 */
public interface InventoryRepository extends JpaRepository<Inventory, Long> {

    /**
     * 根据产品ID查询库存（加悲观锁防止并发修改）
     */
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    Optional<Inventory> findByProductId(Long productId);

    /**
     * 扣减库存（自定义更新操作）
     */
    @Modifying
    @Transactional
    @Query("UPDATE Inventory i SET i.stock = i.stock - :amount WHERE i.productId = :productId AND i.stock >= :amount")
    int reduceStock(Long productId, int amount);

    /**
     * 恢复库存
     */
    @Modifying
    @Transactional
    @Query("UPDATE Inventory i SET i.stock = i.stock + :amount WHERE i.productId = :productId")
    int restoreStock(Long productId, int amount);

}
